﻿using In66.Net.Repository.IRepositories.ISqlSugar;

namespace Maint.Api.Applications.BloomFilters
{
    public class CacheKeyBloomFilter : AbstractBloomFilter
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly IOptions<RedisConfig> _cacheOptions;

        public CacheKeyBloomFilter(
            IOptions<RedisConfig> cacheOptions,
            IRedisProvider redisProvider,
            IDistributedLocker distributedLocker,
            IServiceProvider serviceProvider)
            : base(redisProvider, distributedLocker)
        {
            _serviceProvider = serviceProvider;
            _cacheOptions = cacheOptions;
        }

        public override string Name => CachingConsts.BloomfilterOfCacheKey;

        public override double ErrorRate => _cacheOptions.Value.PenetrationSetting.BloomFilterSetting.ErrorRate;

        public override int Capacity => _cacheOptions.Value.PenetrationSetting.BloomFilterSetting.Capacity;

        public override async Task InitAsync()
        {
            var exists = await ExistsBloomFilterAsync();
            if (!exists)
            {
                var values = new List<string>();
                using var scope = _serviceProvider.CreateScope();
                var dictRepository = scope.ServiceProvider.GetRequiredService<ISugarBaseRepository<Dict>>();
                var dictIds = dictRepository
                    .QueryListByClause(x => x.Pid == 0)
                    .Select(x => x.Id)
                    .ToList();
                if (dictIds.IsNotNullOrEmpty())
                {
                    values.AddRange(dictIds.Select(x => string.Concat(CachingConsts.DictSingleKeyPrefix, CachingConsts.LinkChar, x)));
                }

                var cfgRepository = scope.ServiceProvider.GetRequiredService<ISugarBaseRepository<Dict>>();
                var cfgIds = dictRepository
                    .QueryListByClause(p => p.IsDeleted == false)
                    .Select(x => x.Id)
                    .ToList();
                if (cfgIds.IsNotNullOrEmpty())
                {
                    values.AddRange(cfgIds.Select(x => string.Concat(CachingConsts.CfgSingleKeyPrefix, CachingConsts.LinkChar, x)));
                }

                await InitAsync(values);
            }
        }
    }
}
